package com.ysy.logistics.service.supplier.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysy.common.myenum.StatusEnum;
import com.ysy.common.resp.ResultData;
import com.ysy.logistics.entities.echarts.Series;
import com.ysy.logistics.entities.supplier.SupOrder;
import com.ysy.logistics.entities.supplier.Supplier;
import com.ysy.logistics.entities.supplier.dto.SupOrderDto;
import com.ysy.logistics.entities.supplier.dto.SupOrderGoodsDto;
import com.ysy.logistics.mapper.supplier.SupOrderGoodsMapper;
import com.ysy.logistics.mapper.supplier.SupOrderMapper;
import com.ysy.logistics.mapper.supplier.SupplierMapper;
import com.ysy.logistics.service.supplier.SupOrderService;
import com.ysy.logistics.util.LinearRegression;
import com.ysy.logistics.util.PageInfo;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/25 14:58
 **/
@Service
public class SupOrderServiceImpl extends ServiceImpl<SupOrderMapper, SupOrder> implements SupOrderService {

    @Resource
    private SupOrderMapper supOrderMapper;
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private SupOrderGoodsMapper supOrderGoodsMapper;
    @Override
    @Transactional
    public ResultData saveSupOrderDto(SupOrderDto supOrderDto) {
        SupOrder supOrder = supOrderDto.toSupOrder();
        boolean flag = StringUtils.isBlank(supOrder.getSupplierId())
                || StringUtils.isBlank(supOrder.getPurchaser())
                || CollectionUtils.isEmpty(supOrderDto.getGoodsList());
        if (flag){
            return ResultData.fail("必填项不全");
        }
        //查询出供货商信息
        Supplier supplier = supplierMapper.selectById(supOrder.getSupplierId());
        if (supplier == null) {
            return ResultData.fail("供应商不存在");
        }
        if (supplier.getStatus().equals(StatusEnum.DISABLE.getCode())) {
            return ResultData.fail("供应商状态为停用，不能下单");
        }
        //添加信息
        supOrder.setSupplierName(supplier.getName());
        if(supOrder.getCreateTime()==null){
            supOrder.setCreateTime(new Date());
        }
        //计算总价
        long totalPrice = supOrderDto.getGoodsList().stream()
                .map(supOrderGoods -> supOrderGoods.getGoodsPrice() * supOrderGoods.getGoodsNum())
                .mapToLong(Integer::longValue).sum();
        supOrder.setTotalPrice((int) totalPrice);
        //生成订单编号
        //供货商汉字首字母
        String firstLetter = PinyinUtil.getFirstLetter(supplier.getName(), "").toUpperCase();
        //获取当前年月日小时分秒
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        supOrder.setOrderNum(firstLetter + date);
        //保存订单信息
        supOrderMapper.insert(supOrder);

        //商品添加到订单ID
        supOrderDto.getGoodsList().forEach(supOrderGoods -> {
            supOrderGoods.setId(null);
            supOrderGoods.setOrderId(supOrder.getId());
        });
        //保存商品信息
        supOrderGoodsMapper.insert(supOrderDto.getGoodsList());
        return ResultData.success();
    }

    @Override
    public Page<SupOrder> listByPage(PageInfo<SupOrder> pageInfo) {
       return supOrderMapper.selectByPage(pageInfo.getPage(),pageInfo.getCriteria());
    }

    @Override
    public List<SupOrderGoodsDto> getGoodsListByOrderId(String id) {
        return supOrderGoodsMapper.getGoodsListByOrderId(id);
    }

    @Override
    public ResultData backOrder(String id) {
        if (StringUtils.isBlank(id)){
            return ResultData.fail("订单ID不能为空");
        }
        //查询订单信息
        SupOrder supOrder = supOrderMapper.selectById(id);
        if (Objects.isNull(supOrder)){
            return ResultData.fail("订单不存在");
        }
        //状态为0,1才可以退货
        if (!supOrder.getOrderStatus().equals("0") && !supOrder.getOrderStatus().equals("1")){
            return ResultData.fail("该订单状态不能退货");
        }
        SupOrder update = new SupOrder();
        update.setId(id);
        update.setOrderStatus("3");
        supOrderMapper.updateById(update);
        return ResultData.success();
    }

    @Override
    public ResultData flushOrderStatus() {
        //先模拟退货
        getOrderStatus("3","4");
        //已发货未收货
        getOrderStatus("1","2");
        //未发货
        getOrderStatus("0","1");
        return ResultData.success();
    }

    @Override
    public Series getTotal(List<String> dateArray) {
        Series series = new Series();
        series.setName("采购单");
        List<Long> date = new ArrayList<>();
        //预测使用数据
        List<Double> x = new ArrayList<>();
        List<Double> y = new ArrayList<>();
        //预测坐标
        Double xNext = 2.0;
        if (!CollectionUtils.isEmpty(dateArray)){
            for (int i = 0; i < dateArray.size(); i++) {
              Long total =  supOrderMapper.sumTotalPriceByDate(dateArray.get(i)+" 00:00:00",dateArray.get(i)+" 23:59:59");
              total = Objects.isNull(total)?0:total;
              date.add(total/100);
              x.add(i+1+0.0);
              y.add(total+0.0);
              xNext +=i;
            }
            //数据预测
            double[] train = LinearRegression.train(x, y);
            double predict = LinearRegression.predict(train, xNext);
            predict = predict<0?0:predict;
            date.add((long)predict/100);
        }
        series.setData(date);
        return series;
    }

    /***
     * 模拟更新
     */
    private void getOrderStatus(String nowStatus,String newStatus){
        if (StringUtils.isBlank(nowStatus)|| StringUtils.isBlank(newStatus)){
            return;
        }
        LambdaQueryWrapper<SupOrder> lqw = new LambdaQueryWrapper<>();
        lqw.select(SupOrder::getId).eq(SupOrder::getOrderStatus, nowStatus);
        if (supOrderMapper.exists(lqw)){
            List<SupOrder> supOrders = supOrderMapper.selectList(lqw);
            if (!CollectionUtils.isEmpty(supOrders)){
                List<String> ids = supOrders.stream().map(SupOrder::getId).collect(Collectors.toList());
                flushOrderStatus(ids,newStatus);
            }
        }
    }

    /**
     * 随机更新订单状态
     * @param ids
     * @param orderStatus
     */
    private void flushOrderStatus(List<String> ids,String orderStatus){
        if (CollectionUtils.isEmpty(ids)|| StringUtils.isBlank(orderStatus)){
            return;
        }
        //要更新订单状态的Id

        List<String> collect = ids.stream().filter(id -> generBoolean()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)){
            //不是发货的订单，不需要更新快递号
            if (!"1".equals(orderStatus)){
                LambdaUpdateWrapper<SupOrder> lqw = new LambdaUpdateWrapper<>();
                lqw.in(SupOrder::getId,collect).set(SupOrder::getOrderStatus,orderStatus);
                supOrderMapper.update(null,lqw);
            }else {
                collect.forEach(id -> {
                    SupOrder supOrder = new SupOrder();
                    supOrder.setId(id);
                    supOrder.setOrderStatus(orderStatus);
                    //物流单号
                    String code = generBoolean()?"SF":"YZ";
                    code+= DateUtil.format(new Date(),"yyyyMMddHHmmss");
                    supOrder.setExpressId(code);
                    supOrderMapper.updateById(supOrder);
                });
            }
        }
    }

    public static boolean generBoolean() {
        return  Math.random() > 0.75;
    }

}
